/**     
* @Title: CustomUserService.java   
* @Package me.security.example.security   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年8月22日 下午9:47:56
*/
package me.security.example.security;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import me.security.example.dao.UserDao;
import me.security.example.domain.SysRole;
import me.security.example.domain.SysUser;

/**
 * @ClassName: CustomUserService
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年8月22日 下午9:47:56
 * 
 */
@Service
public class CustomUserService implements UserDetailsService {

	@Autowired
	UserDao userDao;

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CustomUserService.class);

	// 重写loadUserByUsername 方法获得 userdetails 类型用户
	@Override
	public UserDetails loadUserByUsername(String username) {
		SysUser user = userDao.findByUserName(username);
		if (user == null) {
			throw new UsernameNotFoundException("用户名不存在");
		}
		List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
		// 用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。
		for (SysRole role : user.getRoles()) {
			authorities.add(new SimpleGrantedAuthority(role.getName()));
			logger.info("loadUserByUsername: " + user);
		}
		// 用于登录时 @AuthenticationPrincipal 标签取值
		user.setGrantedAuthorities(authorities);
		return user;
	}

}
